 #!/usr/bin/python
 # -*- coding: utf-8 -*-

import iptables


def findword(word,src):	
	return word in src.split()
			
	
f={'filter': ['INPUT', 'FORWARD', 'OUTPUT']}
ff={'filter':[]}
		
def finder(fltr):
			
	rsltli={}
			
	orderno=0
			
	p=iptables.getRules()
	rules=iptables.parseConf(p)

	filterli=('ACCEPT', 'REJECT', 'DROP', 'DENY')
	
	li=iptables.filterDict(rules, fltr)# filter according to the each of the chains in f and ff
					   # this part will work at the second run 


	wordli=("lo", "-p", "-protokol", "-s", "--src", "--source", "-d", "--dst", "--destination", "--sport", "--source-port", "--dport", "--destination-port", "--src-range", "--dst-range", "--port", "-j")		
			
	for x in li["filter"]:# i am interested with only filter table
		
		orderno+=1
			
		for wrd in wordli: # for each keyword in wordli
			if findword(wrd,x): # if it is in the rule
				rsltli[orderno]=x # add as its order  number is keyword and the value is the rule, a dictionary
				li=x.split()
				try:
					index=li.index("-j") # lets check whether there are some other chains i should look
					if li[index+1] not in filterli: 
						try: 
							ff["filter"].index(li[index+1]) # check if there is an entry at the ff
						except:
							ff["filter"].append(li[index+1]) # add it
				except:
					pass
				break						
	return rsltli
								
if __name__=="__main__":
	rslt=[]
	finder(f) # fill the ff

	if len(f["filter"])>1:
		newdic={}
		for x in f["filter"]:
			newdic["filter"]=[x]
			rslt.append(finder(newdic))
			
	if len(ff["filter"])>1:
		newdic={}
		for x in ff["filter"]:
			newdic["filter"]=[x]
			rslt.append(finder(newdic))
			
	for x in rslt:
		print x
	